package javaer.starter.placeholder.character;

import javaer.starter.constants.SymbolEnum;
import javaer.starter.placeholder.ParameterMapping;
import javaer.starter.placeholder.ResultTokenHandler;
import javaer.starter.placeholder.SystemParameter;
import javaer.starter.model.context.StarterContext;

import java.util.HashSet;
import java.util.Set;

/**
 * 查找${}占位符的内容，并替换为freemarker转义后的占位符
 *
 * @author yangzhen
 * @date 2021/12/7 11:28
 * @since 1.0.0
 */
public class ConfigVariableEscapeTokenHandler extends ResultTokenHandler {

    private StarterContext starterContext;

    private Set<ParameterMapping> parameterMappings = new HashSet<>();

    public ConfigVariableEscapeTokenHandler(StarterContext starterContext) {
        this.starterContext = starterContext;
    }

    public String handleToken(String content) {
        buildParameterMapping(content);
        return SymbolEnum.VARIABLE_OPEN_TOKEN_ESCAPE.getSymbol()
                + content
                + SymbolEnum.VARIABLE_CLOSE_TOKEN_ESCAPE.getSymbol();
    }

    private void buildParameterMapping(String content) {
        if (!SystemParameter.isSystemParameter(content)) {
            ParameterMapping parameterMapping = new ParameterMapping(content);
            parameterMappings.add(parameterMapping);
        }
    }

    @Override
    public void handleResult() {
        starterContext.addAllParameter(parameterMappings);
    }

    @Override
    public String getOpenToken() {
        return SymbolEnum.PLACEHOLDER_START.getSymbol();
    }

    @Override
    public String getCloseToken() {
        return SymbolEnum.PLACEHOLDER_END.getSymbol();
    }
}
